package servlet.admin;

import entity.Common;
import entity.Rules;
import net.sf.json.JSONObject;
import service.admin.RulesService;
import service.admin.impl.RulesServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Map;

/**
 * RulesUpdServlet
 *
 * @author 谭文斌
 * @since 2023/9/5
 */
@WebServlet("/admin/rulesUpdServlet")
public class RulesUpdServlet extends HttpServlet {
    RulesService service =new RulesServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");

        String borrow_library = "";

        // 准备返回数据
        int code = 1;
        String msg = "";
        // 获取数据
        // 获取限定图书馆1、2、3
        int num = 0;
        try {
            Map<String, String> libraryMap = Common.getLibraryMap();
            for(String key : libraryMap.keySet()) {
                if(req.getParameter("borrow_library[" +key +"]") != null) {
                    if(num == 0) {
                        borrow_library += key;
                        num++;
                    }else {
                        borrow_library += "、"+key;
                    }
                }
            }
            if(borrow_library.isEmpty()) {
                msg = "允许图书馆不能为空";
            }
        } catch (SQLException e) {
            msg = "获取图书馆失败";
        }
        String borrow_num = req.getParameter("borrow_num");
        String limit_day = req.getParameter("limit_day");
        String overtime_fee = req.getParameter("overtime_fee");
        String id = req.getParameter("id");

        Rules rules = new Rules(Integer.valueOf(id),Integer.valueOf(borrow_num),Integer.valueOf(limit_day),borrow_library,Float.valueOf(overtime_fee));
        int upd =service.upd(rules);
        if (upd==1){
            code=0;
            msg = "修改成功";
        }else {
            msg = "修改失败";
        }
        JSONObject json = new JSONObject();
        json.put("code",code);
        json.put("msg",msg);
        json.put("data",null);

        PrintWriter out = resp.getWriter();
        out.print(json.toString());
    }
}
